import { useCallback } from "react";
import { useSelector, useDispatch } from "react-redux"; // useSelector获取状态值  useDispatch触发reducer
import TotalTypeApi from "../api/totalType"; //引入api
import Creater from "../store/actions"



export const useTotalType = () => {
    //使用useSelector 获取状态机内初始化的totalType状态值   //state对象包含状态机内所有值
    const totalType = useSelector(state => { return state.totalType })
    //解构拿到当前页和每页显示条数
    const { curPage, eachPage } = totalType;
    // 获取dispatch方法，使用其触发reducers 
    const dispatch = useDispatch();


    //获取数商品类型的数据
    const getTotalType = useCallback(async () => {
        console.log("重新渲染");
        //调用api接口 将当前页和每页显示条数作为参数发送请求，data接收返回值
        const data = await TotalTypeApi.get({ curPage, eachPage })
        // 使用dispatch 触发reducer 将请求到的数据传进去作为参数传进去,与初始状态值做合并
        dispatch(Creater.getTatolType(data))
    }, [curPage, eachPage, dispatch])

    //新增商品总类型数据 接收参数是新增的商品总类的名称
    const addTotalType = useCallback(async (totalTypeName) => {
        //调用api接口 发送新增请求 拿回修改成功的状态值
         await TotalTypeApi.addTotalType(totalTypeName)
         
    })
    //删除商品总类型
    const deleteTatolType = useCallback(async (_id) => {
        //调用aip 发送请求删除数据
        await TotalTypeApi.deleteTotalType(_id)

    })
    //修改商品 参数newType是{_id, totalType_name}
    const amendTotalType = useCallback(async (newType) => {
      const data=  await TotalTypeApi.amendTotalType(newType)
      return data
    })




    return [totalType, { getTotalType, addTotalType, deleteTatolType, amendTotalType }]
}
